package pt.utl.ist.project_ccu;
import java.util.ArrayList;
import java.util.HashMap;

import pt.utl.ist.project_ccu.android_libs.Photo;
import pt.utl.ist.project_ccu.android_libs.Tag;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class SearchPhotoResults extends Activity {

	//Array que associa o valor de cada checkbox
	//Cada foto tem uma checkbox

	ArrayList<Photo> _photos;
	HashMap<String,Button> buttons;
	Button selectBtn;
	private TableLayout _tl;

	//Fotos a serem apresentadas na galeria
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		_photos = (ArrayList<Photo>) getIntent().getSerializableExtra("Photos");
		ArrayList<Tag> tags = (ArrayList<Tag>) getIntent().getSerializableExtra("Tags Selected");
		setContentView(R.layout.grid_layout_search_results);
		_tl = (TableLayout) findViewById(R.id.tableLayout);
		GridView gridView = (GridView) findViewById(R.id.grid_view);
        TableRow.LayoutParams params1 = new TableRow.LayoutParams(
        		TableRow.LayoutParams.FILL_PARENT,
                TableRow.LayoutParams.FILL_PARENT);
        TableLayout.LayoutParams params2 = new TableLayout.LayoutParams(
        		TableLayout.LayoutParams.FILL_PARENT,
        		TableLayout.LayoutParams.FILL_PARENT);
        for (Tag t : tags) {
        	TableRow tr = new TableRow(this);
        	TextView text = new TextView(this);
        	text.setText(t.getTagName());
        	tr.addView(text, params1);
        	_tl.addView(tr,params2);
        }
		Display display = this.getWindowManager().getDefaultDisplay();
		int _screenWidth,_screenHeight;
		_screenWidth = display.getWidth();
		_screenHeight = display.getHeight();
		gridView.setAdapter(new ImageAdapter(this,_screenHeight));
		int nr_of_images_width = _screenWidth/3;
		gridView.setColumnWidth(nr_of_images_width);

	}

	public class ImageAdapter extends BaseAdapter {
		int mGalleryItemBackground;
		private Context mContext;
		private LayoutInflater mInflater;
		private int _screenHeight;



		public ImageAdapter(Context c, int screenHeight) {
			mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			mContext = c;
			_screenHeight = screenHeight;
		}

		public int getCount() {
			return _photos.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if(convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.galleryitem_normal, null);
				holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
				convertView.setTag(holder);		
			}
			else {
				holder = (ViewHolder) convertView.getTag();
			}
			
			holder.imageview.setId(position);



			holder.imageview.setImageBitmap(
					decodeSampledBitmapFromResource(getResources(), _photos.get(position).getId(), 500, 500));

			holder.imageview.setLayoutParams(new RelativeLayout.LayoutParams(500, (int) (_screenHeight*0.21)));
			holder.imageview.setScaleType(ImageView.ScaleType.FIT_XY);
			holder.id = position;
			
			final int pos = position;

			holder.imageview.setOnLongClickListener(new OnLongClickListener() {

				@SuppressLint("NewApi")
				public boolean onLongClick(View arg0) {
					/*
					MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
					metaRetriever.setDataSource(getResources().getResourceEntryName(mImageIds[pos]));
					 */
					Intent intent = new Intent(getApplicationContext(),PictureViewer.class);
					intent.putExtra("pictureId", _photos.get(pos).getId());
					startActivity(intent);
					return true;
				}

			});
			
			holder.imageview.setOnClickListener(new OnClickListener() {

				public void onClick(View arg0) {
					/*
					MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
					metaRetriever.setDataSource(getResources().getResourceEntryName(mImageIds[pos]));
					 */
					showImage(_photos.get(pos));
				}

			});

			return convertView;
		}

		public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
			int width = bm.getWidth();
			int height = bm.getHeight();
			float scaleWidth = ((float) newWidth) / width;
			float scaleHeight = ((float) newHeight) / height;
			// CREATE A MATRIX FOR THE MANIPULATION
			Matrix matrix = new Matrix();
			// RESIZE THE BIT MAP
			matrix.postScale(scaleWidth, scaleHeight);

			// "RECREATE" THE NEW BITMAP
			Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
			return resizedBitmap;
		}

		public int getScale(int originalWidth,int originalHeight,
				final int requiredWidth,final int requiredHeight)
		{
			//a scale of 1 means the original dimensions 
			//of the image are maintained
			int scale=1;

			//calculate scale only if the height or width of 
			//the image exceeds the required value.
			if((originalWidth>requiredWidth) || (originalHeight>requiredHeight)) 
			{
				//calculate scale with respect to
				//the smaller dimension
				if(originalWidth<originalHeight)
					scale=Math.round((float)originalWidth/requiredWidth);
				else
					scale=Math.round((float)originalHeight/requiredHeight);

			}

			return scale;
		}
		
	    private void showImage(Photo photo){
	    	
	        Intent pictureViewer = new Intent(getApplicationContext(), PictureViewer.class);
	        pictureViewer.putExtra("photo",photo );
	        startActivityForResult(pictureViewer,0);

	   }

		public int calculateInSampleSize(
				BitmapFactory.Options options, int reqWidth, int reqHeight) {
			// Raw height and width of image
			final int height = options.outHeight;
			final int width = options.outWidth;
			int inSampleSize = 1;

			if (height > reqHeight || width > reqWidth) {
				if (width > height) {
					inSampleSize = Math.round((float)height / (float)reqHeight);
				} else {
					inSampleSize = Math.round((float)width / (float)reqWidth);
				}
			}
			return inSampleSize;
		}
		
		public Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
				int reqWidth, int reqHeight) {

			// First decode with inJustDecodeBounds=true to check dimensions
			final BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeResource(res, resId, options);

			// Calculate inSampleSize
			options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

			// Decode bitmap with inSampleSize set
			options.inJustDecodeBounds = false;
			return BitmapFactory.decodeResource(res, resId, options);
		}
	}

	class ViewHolder {
		ImageView imageview;
		int id;
	}
}

